﻿#region Using References

using System;
using System.Windows;
using Beaker.OpenCube.Dynamic;
using Beaker.OpenCube.Textures;
using Beaker.OpenCube.WorldViewer.Messages;
using Beaker.Services.FileSystem;
using Beaker.Services.Locator;
using GalaSoft.MvvmLight.Messaging;

#endregion

namespace Beaker.OpenCube.WorldViewer
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App
		: Application
	{
		protected override void OnStartup( StartupEventArgs e )
		{
			base.OnStartup( e );

			InitializeServices();

			// register to global messages
			var messenger = ServiceLocator.Current.GetInstance<IMessenger>();
			messenger.Register<ChangeTexturePackMessage>( this, OnChangeTexturePack );
		}

		private static void InitializeServices()
		{
			// set the default service provider of the service locator to the 
			// preinitialized service locator that has all default service implementations
			var locator = PreInitializedServiceLocator.Initialize();

			// register the dynamic game
			locator.RegisterSingletonService( new DynamicGame() );
		}

		protected override void OnExit( ExitEventArgs e )
		{
			var messenger = ServiceLocator.Current.GetInstance<IMessenger>();
			messenger.Unregister( this );
			
			base.OnExit( e );
		}

		/// <summary>
		/// Called when there is a request to change the texture pack
		/// </summary>
		/// <param name="changeMessage"></param>
		private void OnChangeTexturePack( ChangeTexturePackMessage changeMessage )
		{
			// register the new texture pack
			ITexturePack tp = changeMessage.TexturePackToChangeTo;
			PreInitializedServiceLocator.Current.RegisterSingletonService( tp, replace: true );

			// send message to notify others that there is a new texture pack
			var messenger = ServiceLocator.Current.GetInstance<IMessenger>();
			messenger.Send( new TexturePackChangedMessage( tp ) );
		}
	}
}
